package com.seven.micro_service.DAO;

import com.seven.micro_service.bean.Authority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Repository
public class AuthorityDAO {
    JdbcTemplate jdbcTemplate;
    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Authority getAuthorizationWithIdAndService(String id, String service)
    throws RuntimeException{
        return jdbcTemplate.execute((Connection conn) -> {
            // 可以直接使用conn实例，不要释放它，回调结束后JdbcTemplate自动释放:
            // 在内部手动创建的PreparedStatement、ResultSet必须用try(...)释放:
            try (PreparedStatement ps = conn.prepareStatement(
                    "SELECT * FROM authority WHERE id = ? and service = ?")) {
                ps.setObject(1, id);
                ps.setObject(2, service);
                try (ResultSet rs = ps.executeQuery()) {
                    if (rs.next()) {
                        return new Authority(
                                rs.getString("id"), // id
                                rs.getString("service"),
                                rs.getBoolean("authorization")
                        ); // name
                    }
                    throw new RuntimeException("authorization not found by id and service.");
                }
            }
        });
    }
}
